//
//  AppDelegate+JPush.m
//  鸟网
//
//  Created by MiniC on 15/7/30.
//  Copyright (c) 2015年 hongjian_feng. All rights reserved.
//

#import "AppDelegate+JPush.h"
#import "JKNotifier.h"
#import "TLChatViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "IGAgreeOrNotBunding.h"
#import "MessageViewController.h"
#import "FCommentListViewController.h"

static  NSString * jPushAPP_KEY = @"80f0951f241d3d3504b4112c";

@implementation AppDelegate (JPush)

- (void)initJPushWithApplication:(UIApplication *)application withOptions:(NSDictionary *)launchOptions{
    //app关闭状态下，点击推送进来，通过下面的方法才能触发didReceiveRemoteNotification
    NSDictionary *apsDict = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    __weak typeof(self) weakSelf = self;
    if (apsDict) {
        [self application:application didReceiveRemoteNotification:apsDict fetchCompletionHandler:^(UIBackgroundFetchResult result) {
            [weakSelf logicDealWith:apsDict];
        }];
    }
    
    //Remote notification info
    NSDictionary *remoteNotifiInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    //Accept push notification when app is not open
    if (remoteNotifiInfo) {
        [self application:application didReceiveRemoteNotification:remoteNotifiInfo];
    }
    
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeNone|
                                                      UIUserNotificationTypeSound|
                                                      UIUserNotificationTypeAlert|
                                                      UIUserNotificationTypeBadge)
                                          categories:nil];
    
    // iOS10.0以上 新系统需要使用新的代码
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if(!error ){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                });
            }
        }];
    } else {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }

    [JPUSHService setupWithOption:launchOptions appKey:jPushAPP_KEY channel:nil apsForProduction:YES advertisingIdentifier:nil];
    //setLogOFF关闭除了错误信息外的所有Log
    [JPUSHService setLogOFF];
    
    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:KLanguage];
    
    NSLog(@"language%@",language);
    
    NSString *tags = [[NSString alloc]init];
    if ([language containsString:@"zh-Hans"]) {
        tags = @"zh_CN";
    } else tags = @"en_US";
    NSSet *tagSet = [NSSet setWithObject:tags];
    
    [JPUSHService setTags:tagSet completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
    } seq:1];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

#pragma mark - Jpush
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark - 收到消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    application.applicationIconBadgeNumber++;
    
    [self customDealWith:userInfo];
}

#pragma -help
- (void)customDealWith:(NSDictionary *)userInfo {
    //收到消息 个人主页显示小红点逻辑
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MessageNotificationKey" object:userInfo];
    
    UIApplication *application = [UIApplication sharedApplication];
    UIApplicationState applicationState = application.applicationState;
    if(applicationState != UIApplicationStateActive) {
        application.applicationIconBadgeNumber = 0;
//        [self logicDealWith:userInfo];
    } else {
        /*
         type取值：1：评论我的，2：私信，3：购买，4：举报处理，5：反馈回复，6：系统推送，7：推送图片消息8：身份认证审核结果反馈，9：公开作品审核结果反馈，10：解除绑定,11：绑定申请，12：分享邀请
         */
        application.applicationIconBadgeNumber = 0;
        id title = userInfo[@"aps"][@"alert"];// 推送标题
        id type = userInfo[@"type"];// 推送type
        if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"2"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"siMessageNotificationKey" object:userInfo];            
        }
        if ([type isKindOfClass:[NSString class]] && ([type isEqualToString:@"11"] || [type isEqualToString:@"12"]))
        {//绑定申请
            // state 0 : 未处理  1 : 已同意 2 : 已拒绝
            NSString *state = userInfo[@"state"];
            if ([state intValue] != 0) {
                return;
            }
            NSString *uId = userInfo[@"u_id"];
            NSString *macId = userInfo[@"macId"];
            NSString *type = userInfo[@"type"];
            UIActionSheet *actionSheet = [UIActionSheet bk_actionSheetWithTitle:title];
            __weak typeof(self) weakSelf = self;
            [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Approve", nil) handler:^{
                [weakSelf agreeOrNotBunding:uId macId:macId type:type resultType:IGBundingResultTypeAgree];
            }];
            [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Reject", nil) handler:^{
                [weakSelf agreeOrNotBunding:uId macId:macId type:type resultType:IGBundingResultTypeDisAgree];
            }];
            [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Cancel", nil) handler:^{
                
            }];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [actionSheet showInView:kKeyWindow];
            });
        };
        if ([title isKindOfClass:[NSString class]] && ![(NSString *)title isEmpty]) {
//            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//            NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
            __weak typeof(self) weakSelf = self;
            [JKNotifier showNotifer:[NSString stringWithFormat:@"%@", title] name:NSLocalizedString(@"LOCALPUSHAPPNAME", nil) icon:[UIImage imageNamed:@"AppIcon"] dismissAfter:3.0];
            [JKNotifier handleClickAction:^(NSString *name,NSString *detail, JKNotifier *notifier) {
                [JKNotifier dismissAfter:3.0];
                application.applicationIconBadgeNumber -= 1;
                
                [weakSelf logicDealWith:userInfo];
            }];
        }
    }
}

/*
 不同的跳转逻辑：
 type取值：
 1：评论我的
 2：私信 ---------------> 跳转到私信聊天界面
 3：购买
 4：举报处理
 5：反馈回复
 6：系统推送 -----------> 跳转系统消息界面
 7：推送图片消息
 8：身份认证审核结果反馈
 9：公开作品审核结果反馈
 10：解除绑定
 11：绑定申请 ----------> 跳转系统消息界面
 12：分享邀请 ----------> 跳转系统消息界面
 */
- (void)logicDealWith:(NSDictionary *)userInfo {
    id title = userInfo[@"aps"][@"alert"];
    id type = userInfo[@"type"];// 推送type

    if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"1"]) {
        FCommentListViewController  * vc = [[FCommentListViewController alloc]initWithNibName:@"FCommentListViewController" bundle:nil];
        vc.type = 0;
        [UIViewController ig_pushViewController:vc animated:YES];
    } else if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"2"]) {//发送的私信消息
        NSString *uId = userInfo[@"uId"];
        NSString *nike = userInfo[@"nike"];
        TLChatViewController *chatVC = [[TLChatViewController alloc] init];
        chatVC.otherId = uId;
        chatVC.navigationItem.title = nike;
        [UIViewController ig_pushViewController:chatVC animated:YES];
    } else if ([type isKindOfClass:[NSString class]] && [type isEqualToString:@"6"]) {//系统消息字段
        [UIViewController ig_pushViewControllerClass:[MessageViewController class] animated:YES];
    } else if ([type isKindOfClass:[NSString class]] && ([type isEqualToString:@"11"] || [type isEqualToString:@"12"])) {//绑定申请
        // state 0 : 未处理  1 : 已同意 2 : 已拒绝
        NSString *state = userInfo[@"state"];
        if ([state intValue] != 0) {
            return;
        }
        
        NSString *uId = userInfo[@"u_id"];
        NSString *macId = userInfo[@"macId"];
        NSString *type = userInfo[@"type"];
        UIActionSheet *actionSheet = [UIActionSheet bk_actionSheetWithTitle:title];
        __weak typeof(self) weakSelf = self;
        [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Approve", nil) handler:^{
            [weakSelf agreeOrNotBunding:uId macId:macId type:type resultType:IGBundingResultTypeAgree];
        }];
        [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Reject", nil) handler:^{
            [weakSelf agreeOrNotBunding:uId macId:macId type:type resultType:IGBundingResultTypeDisAgree];
        }];
        [actionSheet bk_addButtonWithTitle:NSLocalizedString(@"Cancel", nil) handler:^{
            
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [actionSheet showInView:kKeyWindow];
        });
    }
}

//同意或者拒绝绑定申请和分享绑定
- (void)agreeOrNotBunding:(NSString *)uId macId:(NSString *)macId type:(NSString *)type resultType:(IGBundingResultType)resultType {
    IGAgreeOrNotBunding *agreeOrNotApi = [IGAgreeOrNotBunding new];
    agreeOrNotApi.apiType = resultType;
    agreeOrNotApi.macId = macId;
    agreeOrNotApi.btype = [type isEqualToString:@"11"]?@"1":@"2";
    agreeOrNotApi.applyId = uId;
    __weak typeof(self) weakSelf = self;
    [agreeOrNotApi startWithDecodeClass:[IGAgreeOrNotBundingResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            NSString *tips = @"操作成功";
            if (resultType == IGBundingResultTypeAgree) {
                tips = @"同意绑定成功";
            } else if (resultType == IGBundingResultTypeDisAgree){
                tips = @"拒绝绑定成功";
            }
            [weakSelf presentMessageTips:tips];
        }
    }];
}

@end
